//
//  DMPhotoView.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/3/8.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit

/// 定义Photo的视图间距
let DMPhotoViewMargin:CGFloat = 10
let DMPhotoItemMargin:CGFloat = 5
/// 定义cell的注册标示
let DMPhotoViewReuseIdentifier = "DMPhotoViewReuseIdentifier"

/** 声明一个协议 */
protocol DMPhotoCollectionViewCellDelegate: NSObjectProtocol{
    
    /// 删除指定图片
    func didDeleteIndexImage(Index:Int)
    
}

class DMPhotoView: UICollectionView,UICollectionViewDataSource,DMPhotoCollectionViewCellDelegate,UICollectionViewDelegate{
    
    ///    定义一个闭包
    var closure:(()->())?
    
    ///     私有数组 -- 存放图片
    private lazy var images:[UIImage] = [UIImage]()
    
    var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /** 第一步 */
    private func setUpUI(){
        
        backgroundColor = UIColor.greenColor()
        
        dataSource = self
        
        delegate = self
        
        //  注册cell
        registerClass(DMPhotoCollectionViewCell.self, forCellWithReuseIdentifier: DMPhotoViewReuseIdentifier)
        
        let itemHW = (KUIScreenWidth - 2 * DMPhotoViewMargin - 2 * DMPhotoItemMargin) / 3
        
        flowLayout.itemSize = CGSizeMake(itemHW,itemHW)
        flowLayout.minimumInteritemSpacing = DMPhotoItemMargin
        flowLayout.minimumLineSpacing = DMPhotoItemMargin
        
    }
    
    ///     对外公开一个方法
    func addImages(image:UIImage){
        
        images.append(image)
        
        reloadData()
    }
    
}


extension DMPhotoView{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9{
            return images.count
        }else{
            return images.count + 1
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DMPhotoViewReuseIdentifier, forIndexPath: indexPath) as!DMPhotoCollectionViewCell
        
        if indexPath.item >= images.count{
            
            cell.iconImage = nil
        }else{
            
            cell.iconImage = images[indexPath.item]
        }
        
        //  正向传播数据
        cell.indexPath = indexPath
        cell.delegate = self
        cell.backgroundColor = randomColor
        
        
        return cell
    }
    
    ///     完成删除某个图片操作
    func didDeleteIndexImage(index:Int){
        
        images.removeAtIndex(index)
        reloadData()
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //  判断得是最后一个item点击的时候
        if indexPath.item == images.count{
            //  需要控制器自己调用自己的方法
            closure?()
        }
    }
    
}

class DMPhotoCollectionViewCell: UICollectionViewCell {
    
    weak var delegate:DMPhotoCollectionViewCellDelegate?
    
    var indexPath:NSIndexPath?
    var iconImage:UIImage?{
        
        /** 设置是否要显示删除按钮 */
        didSet{
            if iconImage == nil{
                iconImageView.image = UIImage(named: "compose_pic_add")
                deleteButton.hidden = true
            }else{
                iconImageView.image = iconImage
                deleteButton.hidden = false
            }
        }
        
    }
     override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpInfo()
    }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    private func setUpInfo(){
        contentView.addSubview(iconImageView)
        contentView.addSubview(deleteButton)
        iconImageView.frame = bounds
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(iconImageView.snp_top)
            make.right.equalTo(iconImageView.snp_right)
        }
        
    }
    //MARK:-- 删除按钮
    @objc private func click(){
        if let index = indexPath?.item{
        delegate?.didDeleteIndexImage(index)
        }
    }
    /// 添加的每一个Image
    private lazy var iconImageView:UIImageView = UIImageView()
    /// 右上角"X"按钮
    private lazy var deleteButton:UIButton = {
    
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_card_delete_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
        button.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
    
        return button
    }()
}
